#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
民法典数据服务 - 更新版本
使用正确的MongoDB连接方式
"""

from flask import current_app
from pymongo import TEXT
from pymongo.errors import PyMongoError
from app.database import get_db
import re
import jieba
from datetime import datetime

class CivilCodeService:
    def __init__(self):
        self.db = get_db()
        self.collection = self.db.civil_code_articles if self.db else None
        self.favorites_collection = self.db.user_favorites if self.db else None
        self.history_collection = self.db.search_history if self.db else None
        if self.collection:
            self._ensure_indexes()

    def _ensure_indexes(self):
        """确保所有必要的索引存在"""
        try:
            # 全文搜索索引
            if "civil_code_text_search" not in self.collection.index_information():
                self.collection.create_index([
                    ("content", TEXT),
                    ("title", TEXT),
                    ("explanation", TEXT),
                    ("keywords", TEXT)
                ], name="civil_code_text_search", default_language='none',
                weights={'content': 10, 'title': 5, 'explanation': 3, 'keywords': 8})
                current_app.logger.info("创建全文搜索索引 civil_code_text_search")

            # 关键词数组索引
            if "keywords_array_index" not in self.collection.index_information():
                self.collection.create_index([("keywords", 1)], name="keywords_array_index")
                current_app.logger.info("创建关键词数组索引 keywords_array_index")

            # 条文号唯一索引
            if "article_number_unique" not in self.collection.index_information():
                self.collection.create_index([("article_number", 1)], unique=True, name="article_number_unique")
                current_app.logger.info("创建条文号唯一索引 article_number_unique")

            # 章节复合索引
            if "chapter_compound_index" not in self.collection.index_information():
                self.collection.create_index([
                    ("chapter_info.part", 1),
                    ("chapter_info.chapter_number", 1)
                ], name="chapter_compound_index")
                current_app.logger.info("创建章节复合索引 chapter_compound_index")

            current_app.logger.info("所有索引已确保存在")

        except PyMongoError as e:
            current_app.logger.error(f"创建索引失败: {e}")

    def smart_search(self, query: str, page: int = 1, per_page: int = 20):
        """智能组合搜索法条"""
        if not self.collection:
            return {"articles": [], "pagination": {}, "search_info": {"query": query, "result_count": 0, "strategy": "db_not_connected"}}

        # 1. 尝试全文搜索 (权重最高)
        text_search_results = []
        try:
            text_search_results = list(self.collection.find(
                {"$text": {"$search": query}},
                {"score": {"$meta": "textScore"}}
            ).sort([("score", {"$meta": "textScore"})]).limit(per_page * 2))
            current_app.logger.debug(f"全文搜索 '{query}' 找到 {len(text_search_results)} 条结果")
        except PyMongoError as e:
            current_app.logger.warning(f"全文搜索失败: {e}")

        # 2. 尝试关键词数组搜索 (次高权重)
        keyword_search_results = []
        try:
            # 使用jieba分词，然后精确匹配关键词数组
            seg_list = jieba.lcut_for_search(query)
            keyword_query = {"keywords": {"$in": seg_list}}
            keyword_search_results = list(self.collection.find(keyword_query).limit(per_page * 2))
            current_app.logger.debug(f"关键词搜索 '{query}' 找到 {len(keyword_search_results)} 条结果")
        except PyMongoError as e:
            current_app.logger.warning(f"关键词搜索失败: {e}")

        # 3. 尝试内容正则表达式搜索 (兜底)
        regex_search_results = []
        try:
            regex_query = {"content": {"$regex": query, "$options": "i"}}
            regex_search_results = list(self.collection.find(regex_query).limit(per_page * 2))
            current_app.logger.debug(f"正则搜索 '{query}' 找到 {len(regex_search_results)} 条结果")
        except PyMongoError as e:
            current_app.logger.warning(f"正则搜索失败: {e}")

        # 合并并去重结果，根据相关性排序
        combined_results_map = {}
        for article in text_search_results:
            combined_results_map[article['_id']] = {"article": article, "score": article.get('score', 0) * 3, "strategy": "text"}
        for article in keyword_search_results:
            if article['_id'] not in combined_results_map:
                combined_results_map[article['_id']] = {"article": article, "score": 1 * 2, "strategy": "keyword"}
            else:
                combined_results_map[article['_id']]["score"] += 1 * 2
        for article in regex_search_results:
            if article['_id'] not in combined_results_map:
                combined_results_map[article['_id']] = {"article": article, "score": 1 * 1, "strategy": "regex"}
            else:
                combined_results_map[article['_id']]["score"] += 1 * 1

        sorted_results = sorted(list(combined_results_map.values()), key=lambda x: x['score'], reverse=True)
        final_articles = [item['article'] for item in sorted_results]
        total_results = len(final_articles)

        # 分页
        start_index = (page - 1) * per_page
        end_index = start_index + per_page
        paginated_articles = final_articles[start_index:end_index]

        # 移除MongoDB的_id字段，转换为字符串
        for article in paginated_articles:
            if '_id' in article:
                article['_id'] = str(article['_id'])

        pagination = {
            "page": page,
            "per_page": per_page,
            "total": total_results,
            "pages": (total_results + per_page - 1) // per_page
        }
        search_info = {"query": query, "result_count": total_results, "strategy": "comprehensive"}

        return {"articles": paginated_articles, "pagination": pagination, "search_info": search_info}

    def get_articles_by_chapter(self, part: str, chapter_number: int, page: int = 1, per_page: int = 20):
        """根据编和章节号获取法条"""
        if not self.collection:
            return {"articles": [], "pagination": {}}

        query = {
            "chapter_info.part": part,
            "chapter_info.chapter_number": chapter_number
        }
        total_articles = self.collection.count_documents(query)
        articles = list(self.collection.find(query)
                        .sort("article_number", 1)
                        .skip((page - 1) * per_page)
                        .limit(per_page))

        for article in articles:
            if '_id' in article:
                article['_id'] = str(article['_id'])

        pagination = {
            "page": page,
            "per_page": per_page,
            "total": total_articles,
            "pages": (total_articles + per_page - 1) // per_page
        }
        return {"articles": articles, "pagination": pagination}

    def get_article_by_number(self, article_number: str):
        """根据条文号获取法条详情"""
        if not self.collection:
            return None
        article = self.collection.find_one({"article_number": article_number})
        if article and '_id' in article:
            article['_id'] = str(article['_id'])
        return article

    def get_chapters_list(self):
        """获取所有章节列表"""
        if not self.collection:
            return []
        pipeline = [
            {"$group": {
                "_id": {"part": "$chapter_info.part", "chapter_number": "$chapter_info.chapter_number", "chapter_title": "$chapter_info.chapter_title"},
                "count": {"$sum": 1}
            }},
            {"$sort": {"_id.part": 1, "_id.chapter_number": 1}},
            {"$project": {
                "_id": 0,
                "part": "$_id.part",
                "chapter_number": "$_id.chapter_number",
                "chapter_title": "$_id.chapter_title",
                "article_count": "$count"
            }}
        ]
        chapters = list(self.collection.aggregate(pipeline))
        return chapters

    def get_search_suggestions(self, query: str, limit: int = 10):
        """获取搜索建议"""
        if not self.collection:
            return []
        suggestions = []
        regex_query = {"keywords": {"$regex": query, "$options": "i"}}
        results = self.collection.find(regex_query, {"keywords": 1}).limit(limit * 2)
        for doc in results:
            for keyword in doc.get("keywords", []):
                if query.lower() in keyword.lower() and keyword not in suggestions:
                    suggestions.append(keyword)
                    if len(suggestions) >= limit:
                        break
            if len(suggestions) >= limit:
                break
        return suggestions[:limit]

    def add_favorite(self, article_number: str, user_id: str = "anonymous"):
        """添加收藏"""
        if not self.favorites_collection:
            return False
        try:
            favorite_item = {
                "user_id": user_id,
                "article_number": article_number,
                "created_at": datetime.now()
            }
            self.favorites_collection.update_one(
                {"user_id": user_id, "article_number": article_number},
                {"$set": favorite_item},
                upsert=True
            )
            return True
        except PyMongoError as e:
            current_app.logger.error(f"添加收藏失败: {e}")
            return False

    def remove_favorite(self, article_number: str, user_id: str = "anonymous"):
        """移除收藏"""
        if not self.favorites_collection:
            return False
        try:
            self.favorites_collection.delete_one({"user_id": user_id, "article_number": article_number})
            return True
        except PyMongoError as e:
            current_app.logger.error(f"移除收藏失败: {e}")
            return False

    def get_user_favorites(self, user_id: str = "anonymous", page: int = 1, per_page: int = 20):
        """获取用户收藏列表"""
        if not self.favorites_collection:
            return {"favorites": [], "pagination": {}}
        query = {"user_id": user_id}
        total_favorites = self.favorites_collection.count_documents(query)
        favorites = list(self.favorites_collection.find(query)
                        .sort("created_at", -1)
                        .skip((page - 1) * per_page)
                        .limit(per_page))
        for fav in favorites:
            if '_id' in fav:
                fav['_id'] = str(fav['_id'])
        pagination = {
            "page": page,
            "per_page": per_page,
            "total": total_favorites,
            "pages": (total_favorites + per_page - 1) // per_page
        }
        return {"favorites": favorites, "pagination": pagination}

    def add_search_history(self, query: str, result_count: int = 0, user_id: str = "anonymous"):
        """添加搜索历史"""
        if not self.history_collection:
            return False
        try:
            history_item = {
                "user_id": user_id,
                "query": query,
                "result_count": result_count,
                "created_at": datetime.now()
            }
            self.history_collection.update_one(
                {"user_id": user_id, "query": query},
                {"$set": history_item},
                upsert=True
            )
            return True
        except PyMongoError as e:
            current_app.logger.error(f"添加搜索历史失败: {e}")
            return False

    def get_search_history(self, user_id: str = "anonymous", limit: int = 20):
        """获取用户搜索历史"""
        if not self.history_collection:
            return []
        history = list(self.history_collection.find({"user_id": user_id})
                      .sort("created_at", -1)
                      .limit(limit))
        for item in history:
            if '_id' in item:
                item['_id'] = str(item['_id'])
        return history

    def clear_search_history(self, user_id: str = "anonymous"):
        """清空搜索历史"""
        if not self.history_collection:
            return False
        try:
            self.history_collection.delete_many({"user_id": user_id})
            return True
        except PyMongoError as e:
            current_app.logger.error(f"清空搜索历史失败: {e}")
            return False

civil_code_service = CivilCodeService()
